package com.qianseit.westore.activity.account;

import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.qianseit.westore.BaseDoFragment;
import com.beautymiracle.androidclient.R;
import com.qianseit.westore.Run;
import com.qianseit.westore.http.JsonRequestBean;
import com.qianseit.westore.http.JsonTask;
import com.qianseit.westore.http.JsonTaskHandler;

public class ForgetPasswordFragment extends BaseDoFragment {
	private long countdown_time = 120;

	private EditText mUserNameTV;
	private EditText mVerifyCodeTV;
	private EditText mNewPasswdTV;
	private EditText mConfirmPasswdTV;
	private Button mSubmitButton;
	private View mViewStep1, mViewStep2, mViewStep3;

	private String send_type = "", mobile = "";

	public ForgetPasswordFragment() {
		super();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mActionBar.setTitle(R.string.account_login_forget_passwd);
	}

	@Override
	public void init(android.view.LayoutInflater inflater,
			android.view.ViewGroup container,
			android.os.Bundle savedInstanceState) {
		rootView = inflater.inflate(R.layout.fragment_account_forget_password,
				null);

		mUserNameTV = (EditText) findViewById(R.id.account_forget_password_phone);
		mVerifyCodeTV = (EditText) findViewById(R.id.account_forget_password_verify_code);
		mNewPasswdTV = (EditText) findViewById(R.id.account_forget_password_new);
		mConfirmPasswdTV = (EditText) findViewById(R.id.account_forget_password_confirm);
		mSubmitButton = (Button) findViewById(R.id.account_forget_password_submit);
		mViewStep1 = findViewById(R.id.account_forget_password_step1);
		mViewStep2 = findViewById(R.id.account_forget_password_step2);
		mViewStep3 = findViewById(R.id.account_forget_password_step3);
		mSubmitButton.setOnClickListener(this);
	};

	@Override
	public void onClick(View v) {
		if (v == mSubmitButton) {
			if (mViewStep1.isShown() || mViewStep2.isShown()) {
				if (!TextUtils.isEmpty(mUserNameTV.getText().toString()))
					Run.excuteJsonTask(new JsonTask(), new GetVerifyCodeTask());
			} else if (mViewStep3.isShown()) {
				AccountResetPasswd();
			}
		} else {
			super.onClick(v);
		}
	}

	// 注册用户
	private void AccountResetPasswd() {
		if (TextUtils.isEmpty(mNewPasswdTV.getText())) {
			mNewPasswdTV.requestFocus();
			return;
		}

		if (TextUtils.isEmpty(mConfirmPasswdTV.getText())) {
			mConfirmPasswdTV.requestFocus();
			return;
		}

		if (!TextUtils.equals(mNewPasswdTV.getText(),
				mConfirmPasswdTV.getText())) {
			Run.alert(mActivity, R.string.account_reset_passwd_confirm_failed);
			return;
		}

		Run.excuteJsonTask(new JsonTask(), new ResetPasswdTask());
	}

	// 获取验证码
	private class GetVerifyCodeTask implements JsonTaskHandler {
		@Override
		public JsonRequestBean task_request() {
			showCancelableLoadingDialog();
			return new JsonRequestBean(Run.API_URL,
					"mobileapi.passport.sendPSW").addParams("username",
					mUserNameTV.getText().toString());
		}

		@Override
		public void task_response(String json_str) {
			try {
				JSONObject all = new JSONObject(json_str);
				if (Run.checkRequestJson(mActivity, all)) {
					JSONObject data = all.optJSONObject("data");
					send_type = data.optString("send_type");
					mobile = data.optString(send_type);
					Run.excuteJsonTask(new JsonTask(), new SendVerifyCodeTask());
				} else {
					hideLoadingDialog_mt();
				}
			} catch (Exception e) {
				hideLoadingDialog_mt();
			}
		}
	}

	// 检查验证码
	private class CheckVerifyCodeTask implements JsonTaskHandler {
		@Override
		public JsonRequestBean task_request() {
			showCancelableLoadingDialog();
			return new JsonRequestBean(Run.API_URL,
					"mobileapi.passport.resetpwd_code")
					.addParams("send_type", send_type)
					.addParams("username", mobile)
					.addParams("vcode", mVerifyCodeTV.getText().toString());
		}

		@Override
		public void task_response(String json_str) {
			hideLoadingDialog_mt();
			try {
				JSONObject all = new JSONObject(json_str);
				if (Run.checkRequestJson(mActivity, all)) {
					mHandler.removeMessages(0);
					mSubmitButton.setEnabled(true);
					mSubmitButton.setText(R.string.submit);
					mActionBar.setShowRightButton(false);

					mViewStep1.setVisibility(View.GONE);
					mViewStep2.setVisibility(View.GONE);
					mViewStep3.setVisibility(View.VISIBLE);
				}
			} catch (Exception e) {
			}
		}
	}

	private class ResetPasswdTask implements JsonTaskHandler {
		@Override
		public JsonRequestBean task_request() {
			showCancelableLoadingDialog();
			return new JsonRequestBean(Run.API_URL,
					"mobileapi.passport.resetpassword")
					.addParams("account", mUserNameTV.getText().toString())
					.addParams("login_password",
							mNewPasswdTV.getText().toString())
					.addParams("psw_confirm",
							mConfirmPasswdTV.getText().toString());
		}

		@Override
		public void task_response(String json_str) {
			hideLoadingDialog_mt();
			try {
				JSONObject all = new JSONObject(json_str);
				if (Run.checkRequestJson(mActivity, all)) {
					mActivity.setResult(Activity.RESULT_OK);
					mActivity.finish();
				}
			} catch (Exception e) {
			}
		}
	}

	private class SendVerifyCodeTask implements JsonTaskHandler {
		@Override
		public JsonRequestBean task_request() {
			boolean isMobileType = TextUtils.equals("mobile", send_type);
			JsonRequestBean bean = new JsonRequestBean(Run.API_URL,
					isMobileType ? "mobileapi.passport.send_vcode_sms"
							: "mobileapi.passport.send_vcode_email");
			bean.addParams("uname", mobile);
			bean.addParams("type", "forgot");
			return bean;
		}

		@Override
		public void task_response(String json_str) {
			hideLoadingDialog_mt();
			try {
				JSONObject all = new JSONObject(json_str);
				if (Run.checkRequestJson(mActivity, all)) {
					// 用户提示语
					int messageId = R.string.account_forget_password_step2_message;
					((TextView) findViewById(R.id.account_forget_password_step2_message))
							.setText(mActivity.getString(messageId, mobile));
					// 倒计时
					countdown_time = 120;
					mHandler.sendEmptyMessage(0);
					mActionBar.setRightTitleButton(R.string.next_step,
							new OnClickListener() {
								@Override
								public void onClick(View v) {
									if (!TextUtils.isEmpty(mVerifyCodeTV
											.getText().toString()))
										Run.excuteJsonTask(new JsonTask(),
												new CheckVerifyCodeTask());
								}
							});

					mViewStep1.setVisibility(View.GONE);
					mViewStep2.setVisibility(View.VISIBLE);
					mViewStep3.setVisibility(View.GONE);
					mSubmitButton.setEnabled(false);
				}
			} catch (Exception e) {
				Run.alert(mActivity, "验证码下发失败！");
			}
		}
	}

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// 倒计时结束
			if (--countdown_time <= 0) {
				mSubmitButton.setEnabled(true);
				mSubmitButton.setText(R.string.account_regist_get_verify_code);
				return;
			}

			mSubmitButton.setText(mActivity.getString(
					R.string.account_forget_password_step2_countdown,
					countdown_time));
			sendEmptyMessageDelayed(0, 1000);
		};
	};
}
